package com.Iconcat.system.controller;

import com.Iconcat.system.entity.CatTokeninfo;
import com.Iconcat.system.entity.CatUser;
import com.Iconcat.system.response.Result;
import com.Iconcat.system.service.CaptchaService;
import com.Iconcat.system.service.CatTokeninfoService;
import com.Iconcat.system.service.CatUserService;
import com.Iconcat.system.util.ImageCodeUtil;
import com.Iconcat.system.util.JwtUtil;
import com.Iconcat.system.util.Md5Util;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.net.ssl.HandshakeCompletedEvent;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/CatUser")
@CrossOrigin
@Api(value = "系统用户模块",tags = "系统用户接口")
public class CatUserController {
    // 获取日志记录器
    private static final Logger logger = LoggerFactory.getLogger(CatUserController.class);
    @Resource
    private CatUserService catUserService;
    @Resource
    private CaptchaService captchaService;
    @Resource
    private CatTokeninfoService catTokeninfoService;

    private static String globalCaptcha;
    @GetMapping("/userAll")
    public Result UserAll(@RequestParam(required = true,defaultValue = "1") Integer current,
                          @RequestParam(required = true,defaultValue = "6")Integer size,
                          @RequestParam(required = false)String searchKeyword
                          ){
        Page<CatUser> page=new Page<>(current,size);
        LambdaQueryWrapper<CatUser> queryWrapper=new LambdaQueryWrapper<>();
        // 如果搜索关键字不为空，进行模糊查询
        if (searchKeyword != null && !searchKeyword.isEmpty()) {
            queryWrapper.like(CatUser::getUserName, searchKeyword)
                    .or().like(CatUser::getPhoneNumber, searchKeyword);
            // 如果有其他需要查询的字段，可以继续添加 .or().like(...)
        }
        Page<CatUser> userPage=catUserService.page(page,queryWrapper);
        return Result.ok().data("cgtUser",userPage);
    }
    @GetMapping("/{id}")
    public Result queryByKey(@PathVariable("id") Integer user_id){
        CatUser id=catUserService.getById(user_id);
        return Result.ok().data("user", id);
    }
    @PostMapping("/updateById")
    public Result updateById(@RequestBody CatUser cgtUser)throws Exception{
       Boolean user=catUserService.updateById(cgtUser);
       if (user){
           return Result.ok().message("修改成功");
       }
       else {
           return  Result.error().message("修改失败");
       }
    }
    @PostMapping("/addUser")
    public Result addUser(@RequestBody CatUser catUser){
        try {
            catUserService.save(catUser);
            List<CatUser> list =catUserService.list();
            return Result.ok().data("user",list);
        }catch (Exception e){
            //打印日志
            return Result.error();
        }
    }

    @PostMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam("cids") List<Integer> cids)throws Exception{
        Boolean r=catUserService.removeByIds(cids);
        System.out.println(cids);
        if (r){
            return Result.ok().message("删除成功");
        }
        else {
            return  Result.error().message("删除失败");
        }

//        QueryWrapper<CgtUser> wrapper=new QueryWrapper<>();
//        wrapper.in("user_id",cids);
//        System.out.println(cids);
//       Boolean ids=cgtUserService.removeByIds();
//
//        System.out.println(ids);
//        if (ids==false){
//            return Result.ok().message("删除成功");
//        }
//        else {
//            return  Result.error().message("删除失败");
//        }

    }
    @PostMapping("/delete/id")
    public Result deleteById(@RequestParam("user_id") Integer user_id) throws Exception{
     Boolean  user=catUserService.removeById(user_id);

        if (user){
            return Result.ok().message("删除成功");
        }

        else{
            boolean hasImportantData = checkImportantData(user_id);

            if (hasImportantData) {
                return Result.warn().message("会员存在重要数据");
            } else {
                return Result.error().message("删除失败");
            }
        }
    }
    // 检查会员是否存在重要数据的方法，具体实现需要根据实际情况编写
    private boolean checkImportantData(Integer user_id) {
        // 在这里添加检查会员存在重要数据的逻辑
        // 返回 true 表示存在重要数据，返回 false 表示不存在重要数据
        // 可以根据需要查询数据库等操作
        return false;
    }
    @GetMapping("/get/{user_id}")
    public Result getUserById(@PathVariable("user_id") Integer user_id) {
        CatUser user = catUserService.getById(user_id);
        if (user != null) {
            return Result.ok().data("user", user);
        } else {
            return Result.error().message("未找到用户");
        }
    }


    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody Map<String, String> requestBody, HttpServletRequest request) throws IOException {
        String user_phone=requestBody.get("user_phone");
        String user_password=requestBody.get("user_password");
        String captcha=requestBody.get("captcha");
        if (user_phone == null || user_phone.isEmpty() || user_password == null || user_password.isEmpty() || captcha == null || captcha.isEmpty()) {
            return Result.error().message("用户手机号、密码和验证码不能为空");
        }

        // 获取静态变量中存储的验证码
        String storedCaptcha = getGlobalCaptcha();
        if (!captchaService.validateCaptcha(captcha, storedCaptcha)) {
            return Result.error().message("验证码不正确");
        }
        String password=Md5Util.md5(user_password);
        QueryWrapper<CatUser> wrapper=new QueryWrapper<>();
        wrapper.eq("phone_number",user_phone);
        wrapper.eq("user_password",password);
        CatUser user=catUserService.getOne(wrapper);

        if (user==null||!user.getPhoneNumber().equals(user_phone)){
            return Result.error().message("用户不存在");
        }
        logger.info(user.getPhoneNumber());
        logger.info(user.getUserPassword());
        if(!user.getUserPassword().equals(password)){
            return Result.error().message("密码错误");
        }


        String token= JwtUtil.setToken(user.getPhoneNumber());
        CatTokeninfo catTokeninfo=new CatTokeninfo();
        catTokeninfo.setToken(token);
        catTokeninfo.setInfo(user.getUserName());
        int rowsAffected= catTokeninfoService.addUser(catTokeninfo);
        Map<String, Object> response = new HashMap<>();
        response.put("user", user);
        response.put("token",token);
//        map.put("user",user.getUserPassword());
        System.out.println(response);

        if(rowsAffected >0){

            return Result.ok().data("user",user).message("登录成功").token("token",token);
        }
      else{
          return Result.error().message("登录失败");
        }

    }
    // 生成验证码图片
    @GetMapping("/captcha")
    public Result getCaptchaImage() {
        String code = ImageCodeUtil.makeCode(); // 生成验证码字符串
        // 存储验证码到静态变量
        globalCaptcha = code;
        BufferedImage image = ImageCodeUtil.makeImage(code); // 生成验证码图片

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image,"jpeg", baos);
            byte[] imageData = baos.toByteArray();
            String base64Image = Base64.getEncoder().encodeToString(imageData);
            System.out.println("Session: " + code);
            return Result.ok().data("captchaImage", base64Image);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error().message("验证码生成失败");
        }
    }
    @PostMapping("/logout")
    public Result logout(@RequestBody Map<String, String> requestBody) {
        String token = requestBody.get("token");// 假设从请求中获取用户名

        if (token != null && !token.isEmpty()) {
            // 根据前端提交的 token 删除数据库中的相应记录
            int rowsAffected = catTokeninfoService.deleteUser(token);

            if (rowsAffected > 0) {
                return Result.ok().message("退出成功");
            } else {
                return Result.error().message("退出失败，无效的 token");
            }
        } else {
            return Result.error().message("退出失败，未提供有效的 token");
        }
    }

    @PostMapping("/register")
    public Result registerUser(@RequestBody Map<String, String> request,HttpServletRequest httpRequest)throws Exception {
        String phoneNumber = request.get("phoneNumber");
        String password = request.get("password");
        String confirmPassword = request.get("confirmPassword");
        String inviteCode = request.get("inviteCode");
        String userInputCaptcha = request.get("captcha");

        if (StringUtils.isAnyBlank(phoneNumber, password, confirmPassword, userInputCaptcha)) {
            return Result.error().message("所有注册字段必须填写");
        }
        // 获取静态变量中存储的验证码
        String storedCaptcha = getGlobalCaptcha();
        System.out.println("Session ID: " + storedCaptcha);
        if (!captchaService.validateCaptcha(userInputCaptcha, storedCaptcha)) {
            return Result.error().message("验证码不正确");
        }

        // 使用QueryWrapper检查手机号是否已注册
        QueryWrapper<CatUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone_number", phoneNumber);
        CatUser existingUser = catUserService.getOne(queryWrapper);

        if (existingUser != null) {
            return Result.userAlreadyExist().message("手机号已经注册");
        }

        // 检查密码和确认密码是否一致
        if (!password.equals(confirmPassword)) {
            return Result.error().message("密码和确认密码不一致");
        }
        Md5Util.md5(password);
        // 执行用户注册逻辑
        CatUser newUser = new CatUser();
        String token= JwtUtil.setToken(newUser.getPhoneNumber());
        CatTokeninfo catTokeninfo=new CatTokeninfo();
        catTokeninfo.setToken(token);
        newUser.setPhoneNumber(phoneNumber);
        newUser.setUserPassword(Md5Util.md5(password));
        newUser.setInviteCode(inviteCode);
        newUser.setMembershipStatus("普通会员");
        newUser.setTeamMemberStatus("普通团员");
        // 保存用户信息到数据库（当你的服务准备好时，请取消下一行的注释）
         catUserService.save(newUser);

        return Result.ok().data("newUser",newUser).message("注册成功").token("token",token);
    }
    // 获取静态变量中的验证码
    private String getGlobalCaptcha() {
        return globalCaptcha;
    }

}
